import multiprocessing
from multiprocessing import Manager
import time
from lan_discovery import ThreadDeviceAgent, ThreadDeviceServer

def run_agent():
    agent = ThreadDeviceAgent(name="AlphaBot", info="Jetson Nano")
    agent.start()

def run_server(shared_devices):
    server = ThreadDeviceServer(shared_devices)
    server.start()

if __name__ == "__main__":
    try:
        manager = Manager()
        shared_devices = manager.dict()
        
        # 启动服务端
        server_process = multiprocessing.Process(target=run_server, args=(shared_devices,))
        server_process.start()

        # 启动设备端
        agent_process = multiprocessing.Process(target=run_agent)
        agent_process.start()

        # 在主进程中可以读取 shared_devices 内容
        try:
            while True:
                print("在线设备：", list(shared_devices.values()))
                time.sleep(5)
        except KeyboardInterrupt:
            print("\n[退出] 正在关闭所有进程...")
            # 优雅退出子进程
            server_process.terminate()
            agent_process.terminate()
            # 等待进程结束
            server_process.join(timeout=5)
            agent_process.join(timeout=5)
            print("[完成] 所有进程已关闭")
    except Exception as e:
        print(f"[错误] 程序运行异常: {e}")
    finally:
        # 确保进程被清理
        if 'server_process' in locals() and server_process.is_alive():
            server_process.terminate()
        if 'agent_process' in locals() and agent_process.is_alive():
            agent_process.terminate()
